from __future__ import print_function  # 确保这行是文件中的第一行内容
import requests
import asyncio
from app.core.config import settings
import datetime, hashlib, hmac, json
import requests, urllib
from volcengine.imagex.v2.imagex_service import ImagexService

async def upload_file(file_document: str, file_path: str, url: str):
    """
    发送一个 POST 请求以将文件上传到指定的端点。

    :param url: 文件来源的 URL（例如 'https://example.com/file.mp4'）。
    :return: POST 请求的响应对象。
    """
    # 构建请求的完整 URL
    endpoint = f"https://luzhuoai.tos-cn-beijing.volces.com/{file_document}/{file_path}?fetch"
    
    # 设置请求头
    headers = {
        "x-tos-acl": "public-read",  # 设定文件访问权限为公开可读
        "Date": "",  # 日期字段可以为空
        "x-storage-class": "STANDARD",  # 设置存储类型为低频访问（IA）
        "Content-Type": "application/json",  # 请求内容类型为 JSON
        "x-tos-grant-read": ""
    }
    
    # 设置请求体数据
    data = {
        "URL": url,  # 要下载的文件 URL
        "IgnoreSameKey": True  # 忽略同名文件的检查
    }

    try:
        # 发送 POST 请求
        response = requests.post(endpoint, headers=headers, json=data)
        response.raise_for_status()  # 如果响应状态码是错误（4xx 或 5xx），引发异常
        oss_url = f'https://luzhuoai.tos-cn-beijing.volces.com/{file_document}/{file_path}'
        response_code = {
            "code": response.status_code,
            "etag": response.text,
            "oss_url": oss_url
        }
        return response_code
    except requests.exceptions.RequestException as e:
        # 捕获并打印请求异常
        print(f"请求发生错误: {e}")
        return None

def huoshan_oss_token():
    set_ak = settings.OSS_ACCESS_AK
    set_st = settings.OSS_ACCESS_SK
    imagex_service = ImagexService()
    imagex_service.set_ak(set_ak)
    imagex_service.set_sk(set_st)
    service_ids = ['imagex service id']
    tag = dict()

    # 获取上传授权
    resp = imagex_service.get_upload_auth(service_ids, tag=tag)
    respone = {
        "AccessKeyID": resp.access_key_id,
        "SecretAccessKey": resp.secret_access_key,
        "SessionToken" : resp.session_token
    }
    return respone
def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(key.encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'request')
    return kSigning

def getSignHeaders(method, service, host, region, request_parameters, access_key, secret_key):
    contenttype = 'application/x-www-form-urlencoded'
    accept = 'application/json'
    t = datetime.datetime.utcnow()
    xdate = t.strftime('%Y%m%dT%H%M%SZ')
    datestamp = t.strftime('%Y%m%d')
    # ************* 1: 拼接规范请求串 *************
    canonical_uri = '/'
    canonical_querystring = request_parameters
    canonical_headers = 'content-type:'+ contenttype + '\n' +'host:' + host + '\n' + 'x-date:' + xdate + '\n'
    signed_headers = 'content-type;host;x-date'
    payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()
    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    # ************* 2：拼接待签名字符串 *************
    algorithm = 'HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'request'
    string_to_sign = algorithm + '\n' +  xdate + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

    # ************* 3：计算签名 *************
    signing_key = getSignatureKey(secret_key, datestamp, region, service)
    signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()

    # ************* 4：添加签名到请求header中 *************
    authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
    headers = {'Accept': accept, 'Content-Type': contenttype, 'X-Date': xdate, 'Authorization': authorization_header}
    return headers

def huoshan_oss_token():
    # 基础参数设置
    method = 'GET'
    service = 'sts'
    host = 'open.volcengineapi.com'
    region = 'cn-beijing'
    endpoint = 'https://open.volcengineapi.com'
    # 请根据实际情况填写你的 AccessKey 和 SecretKey
    # access_key = 'AKLTYmZmZjg5NDYyZTBmNDZhYmJiMDZiOGIyNzk0ODU4YmE'
    # secret_key = 'TW1FeFlUSm1NalkwTlRSa05HRTRNMkkwTTJJMFpqVXpZekl3T0dKbU56RQ=='
    access_key = settings.OSS_ACCESS_AK
    secret_key = settings.OSS_ACCESS_SK
    # query_parameters = {
    #     'Action': 'AssumeRole',
    #     'RoleSessionName': 'hans262',
    #     'RoleTrn': 'trn:iam::2100905332:role/sts',
    #     'Version': '2018-01-01'
    # }
    query_parameters = {
        'Action': 'AssumeRole',
        'RoleSessionName': 'guang9527',
        'RoleTrn': settings.TOS_RoleTrn,
        'Version': '2018-01-01'
    }
    request_parameters = urllib.parse.urlencode(query_parameters)
    headers = getSignHeaders(method, service, host, region, request_parameters, access_key, secret_key)
    request_url = endpoint + '?' + request_parameters

    r = requests.get(request_url, headers=headers)
    resp = r.json()
    print(r.text)
    credentials = resp["Result"]["Credentials"]
    response = {
        "AccessKeyID": credentials["AccessKeyId"],
        "SecretAccessKey": credentials["SecretAccessKey"],
        "SessionToken": credentials["SessionToken"]
    }
    return response